package com.qf.im.controller;


import com.qf.im.base.BaseController;
import com.qf.im.base.R;
import com.qf.im.entity.User;
import com.qf.im.service.UserService;
import com.qf.im.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户表(User)表控制层
 *
 * @author makejava
 * @since 2023-10-25 10:20:37
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController<UserService> {

    @PostMapping("/register")
    public R register(@Validated User user){
        log.debug("【User Register】用户注册...{}", user);
        //调用业务层保存用户信息
        getBaseService().save(user);
        return R.succ();
    }

    /**
     * 登录的请求
     * @return
     */
    @PostMapping("/login")
    public R login(String username, String password){
        log.debug("【User Login】用户登录... {} {}", username, password);
        //登录的业务
        User user = getBaseService().login(username, password);
        //获取用户的登录信息，使用jwt封装一层，生成一个令牌Token（字符串）
        String jwtToken = JwtUtils.createJwtToken()
                .add("uid", user.getId())
                .add("nickname", user.getNickname())
                .add("header", user.getHeader())
                .build();

        //将jwt令牌返回给客户端
        return R.succ(jwtToken);
    }

    /**
     * 查询用户的头像
     * @param username
     * @return
     */
    @RequestMapping("/queryUserHeader")
    public R queryUserHeader(String username) {
        User user = getBaseService().queryUserInfo(username);
        return R.succ(user.getHeader());
    }

    /**
     * 搜索用户
     * @return
     */
    @GetMapping("/searchUsers")
    public R searchUsers(String keyword){
        return R.succ(getBaseService().searchUser(keyword));
    }

}

